package com.crawler.harbour.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crawler.harbour.common.DockCode;
import com.crawler.harbour.dto.LoginParamsDto;
import com.crawler.harbour.entity.XmxhdShipmentReportForm;
import com.crawler.harbour.model.Notice;
import com.crawler.harbour.model.ShipmentNew;
import com.crawler.harbour.service.INoticeService;
import com.crawler.harbour.service.IShipmentNewService;
import com.crawler.harbour.utils.AESUtil;
import com.crawler.harbour.utils.DateUtils;
import com.crawler.harbour.utils.LoginUtil;
import com.crawler.harbour.utils.RuoKuai;
import com.crawler.harbour.utils.StorageDay;
import com.crawler.harbour.utils.UrlUtil;
import com.crawler.utils.BeanUtils;
import com.crawler.utils.RedisManager;
import com.crawler.utils.StringUtils;

import net.dongliu.requests.Parameter;
import net.dongliu.requests.Requests;
import net.dongliu.requests.Response;
import net.dongliu.requests.Session;

/**
 * 厦门新海达
 *
 * @author wbsheng
 * @create 2018-04-02 9:25
 **/
@Service
@Lazy(false)
public class XMXHDTask extends StorageDay{

    private static final Logger LOGGER = LoggerFactory.getLogger(XMXHDTask.class);
    @Autowired
    IShipmentNewService shipmentNewService;
    @Autowired
    private INoticeService noticeService;
    
    /**
     * 每天00点30分执行
     * 新海达码头船期预报表
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void shipmentReportFormTask() {
    	if(!RedisManager.lock("ship:shipmentReportFormTask", 0)) {
    		return;
    	}
        Session session = Requests.session();
        //登入并获取cookie数据
        String jsTicket = LoginUtil.getXHCTJsTicket(session, LoginParamsDto.getLoginParams(UrlUtil.XMXHDLOGIN, UrlUtil.XMXHDVALIDATE, null, "XHD_WEB_JsTicket"));
        System.out.println(jsTicket);
        String startDate = DateUtils.formatDate(new Date(), "yyyy-MM-dd 00:00:00");
        int year = Integer.valueOf(DateUtils.getYear());
        int month = Integer.valueOf(DateUtils.getMonth());
        String endDate = DateUtils.formatDate(DateUtils.getAfter(new Date(), 7));
        //请求参数组装
        Map<String, String> queryParam = new HashMap<>();
        queryParam.put("view", AESUtil.xhct("XhdForecastQuery", jsTicket));
        queryParam.put("encrpyCls", AESUtil.xhct("*", jsTicket));
        queryParam.put("sortname", AESUtil.xhct("日期", jsTicket));
        queryParam.put("page", "1");
        queryParam.put("pagesize", "9999");
        queryParam.put("sortorder", AESUtil.xhct("日期", jsTicket));
        queryParam.put("orginencrpyCondition", AESUtil.xhct("{}", jsTicket));
        queryParam.put("encrpyCondition", AESUtil.xhct("{\"groups\":[{},{\"op\":\"and\",\"rules\":[{\"op\":\"greaterorequal\",\"field\":\"TRUNC(b.eta)\",\"value\":\"" + startDate + "\",\"type\":\"date\"},{\"op\":\"lessorequal\",\"field\":\"TRUNC(b.eta)\",\"value\":\"" + endDate + "\",\"type\":\"date\"}]}],\"op\":\"and\"}", jsTicket));
        Response<String> queryResponse = session.post(UrlUtil.XMXHDQUERY).forms(queryParam).headers(Parameter.of("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")).send().toTextResponse();
        String queryResponBody = queryResponse.getBody();
        JSONObject queryJsonObject = JSONObject.parseObject(queryResponBody);
        Integer total = queryJsonObject.getInteger("Total");
        JSONArray rows = queryJsonObject.getJSONArray("Rows");
        //转化成javabean
        List<XmxhdShipmentReportForm> xmxhdShipmentReportFormDtos = JSONObject.parseArray(rows.toJSONString(), XmxhdShipmentReportForm.class);
        List<ShipmentNew> shipmentNewList = new ArrayList<>();
        Date date = new Date();
        for (XmxhdShipmentReportForm form : xmxhdShipmentReportFormDtos) {
            form.setCreateDate(date);
            //船名+进口或者出口+航次
            String hashStr = RuoKuai.MD5(form.getShipName() + form.getImportAndExport() + form.getVoyage());
            form.setId(hashStr);
        }
        LOGGER.info(total + " " + xmxhdShipmentReportFormDtos.size());
        List<String> IdList =new ArrayList<>();
        for (XmxhdShipmentReportForm shipMent : xmxhdShipmentReportFormDtos) {
        	ShipmentNew shipmentNew = new ShipmentNew();
            String hashStr = RuoKuai.MD5(DockCode._XHD+shipMent.getShipName()+shipMent.getVoyage());
            shipMent.setId(hashStr);
            shipmentNew.setId(hashStr);
            ShipmentNew temp = shipmentNewService.selectById(hashStr);
            Notice notice = new Notice();
            notice.setPortNo(DockCode._XHD);
            shipmentNew.setWharfName("新海达码头");
            notice.setShipCnName(shipMent.getShipName());
            if ("出口".equals(shipMent.getImportAndExport())) {
                notice.setCkShipTimer(shipMent.getVoyage());
                shipmentNew.setSailingDate(convertTime(shipMent.getExpectedDate(),year,month));
                shipmentNew.setType(2);
            } else {
                notice.setJkShipTimer(shipMent.getVoyage());
                shipmentNew.setSailingDate(convertTime(shipMent.getExpectedDate(),year,month));
                shipmentNew.setType(1);
            }
            notice.setJkSailingDate(convertTime(shipMent.getExpectedDate(),year,month));
            notice.setCkSailingDate(convertTime(shipMent.getExpectedDate(),year,month));
            notice.setIntoDate(convertTime(shipMent.getOpeningTime(),year,month));
            notice.setOffDate(convertTime(shipMent.getCutBoxTime(),year,month));
            notice.setStatus(0);
            if(StringUtils.isNullOrEmpty(notice.getShipName())) {
            	notice.setShipName(notice.getShipCnName());
            }
            notice.setCreateTime(date);
            shipmentNew.setShipTimer(shipMent.getVoyage());
            shipmentNew.setSvcName(shipMent.getRoute());
            shipmentNew.setLiner(shipMent.getShipCompany());
            shipmentNew.setBerthDate(shipMent.getActualBerthing());
            BeanUtils.copyProperties(notice,shipmentNew , "id","status","type","shipTimer","sailingDate");
            boolean isOk = true;
            if(temp!=null&& IdList.contains(temp.getId())) {
        		isOk = false;
        	}
		    if(isOk) {
                if (temp!=null&&shipmentNew.getType() == 1 && !temp.getSailingDate().equals(shipmentNew.getSailingDate())) {
                	if(toString(temp.getSailingDate()).equals("")) {
                		notice.setType(0);
                	}else {
                		notice.setType(4);
                	}
                    notice.setId(null);
                    notice.setOrigValue(temp.getSailingDate());
                    noticeService.insert(notice);
                } 
                if (temp!=null&&shipmentNew.getType() == 2 && !temp.getSailingDate().equals(shipmentNew.getSailingDate())) {
                	if(toString(temp.getSailingDate()).equals("")) {
                		notice.setType(0);
                	}else {
                		notice.setType(1);
                    }
                    notice.setId(null);
                    notice.setOrigValue(temp.getSailingDate());
                    noticeService.insert(notice);
                } 
                if (temp!=null&&shipmentNew.getType() == 2 && !temp.getOffDate().equals(shipmentNew.getOffDate())) {
                    notice.setType(2);
                    notice.setId(null);
                    notice.setOrigValue(temp.getOffDate());
                    noticeService.insert(notice);
                } 
                if (temp!=null&&shipmentNew.getType() == 2 && !temp.getIntoDate().equals(shipmentNew.getIntoDate())) {
                    notice.setType(3);
                    notice.setId(null);
                    notice.setOrigValue(temp.getIntoDate());
                    noticeService.insert(notice);
                }
                if(temp!=null) {
                	IdList.add(temp.getId());
                }
	        }
            shipmentNewList.add(shipmentNew);
        }
        shipmentNewService.insertOrUpdateAllColumnBatch(shipmentNewList, xmxhdShipmentReportFormDtos.size());
        LOGGER.info("厦门海通船期--增加完毕");
    }
    
    
    private String convertTime(String date,int year,int month) {
    	if(StringUtils.isNullOrEmpty(date)) {
    		return "";
    	}
    	int dataMonth = Integer.valueOf(date.substring(0, 2));
    	return (dataMonth < month ? year+1 : year)+"-"+date;
    	
    }
    private String toString(Object data) {
    	if(data==null) {
    		return "";
    	}
    	return data.toString();
    	
    }
}
